package com.erp.gather.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.gather.domain.ErpCollectProductCategory;
import com.erp.gather.domain.ErpSellerStoreGroup;
import com.erp.gather.domain.ErpSellerStoreProductGroup;
import com.erp.gather.domain.bo.ErpSellerStoreGroupBo;
import com.erp.gather.domain.vo.ErpSellerStoreGroupVo;
import com.erp.gather.mapper.ErpCollectProductCategoryMapper;
import com.erp.gather.mapper.ErpSellerStoreGroupMapper;
import com.erp.gather.mapper.ErpSellerStoreProductGroupMapper;
import com.erp.gather.mapper.ErpSellerStoreProductMapper;
import com.erp.gather.service.IErpSellerStoreGroupService;
import com.erp.gather.service.IErpSellerStoreProductGroupService;
import com.ruoyi.ae.api.RemoteAeStoreGroupService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.gather.api.domain.ErpSellerStoreProduct;
import com.ruoyi.gather.api.domain.dto.SendProductGroupDto;
import com.ruoyi.gather.api.domain.dto.StoreGroupDto;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户店铺商品分组Service业务层处理
 *
 * @author erp
 * @date 2023-11-08
 */
@RequiredArgsConstructor
@Service
public class ErpSellerStoreGroupServiceImpl implements IErpSellerStoreGroupService {

    private final ErpSellerStoreGroupMapper baseMapper;
    private final IErpSellerStoreProductGroupService erpSellerStoreProductGroupService;
    private final ErpSellerStoreProductGroupMapper erpSellerStoreProductGroupMapper;
    private final ErpCollectProductCategoryMapper erpCollectProductCategoryMapper;
    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
    @Resource
    RemoteAeStoreGroupService remoteAeStoreGroupService;
    @Resource
    RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    private RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);
    /**
     * 查询用户店铺商品分组
     */
    @Override
    public ErpSellerStoreGroupVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询用户店铺商品分组列表
     */
    @Override
    public TableDataInfo<ErpSellerStoreGroupVo> queryPageList(ErpSellerStoreGroupBo bo, PageQuery pageQuery) {
//        LambdaQueryWrapper<ErpSellerStoreGroup> lqw = buildQueryWrapper(bo);
        Long userId = SecurityUtils.getUserId();
        if (userId != 1) {
            bo.setUserId(SecurityUtils.getUserId());
        }
        Page<ErpSellerStoreGroupVo> result = baseMapper.queryPageList(pageQuery.build(), bo);
        List<ErpSellerStoreGroupVo> records = result.getRecords();
        for (ErpSellerStoreGroupVo group : records) {
            group.setChildGroup(baseMapper.queryChildGroupByGroupId(group.getGroupId()));
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询用户店铺商品分组列表
     */
    @Override
    public List<ErpSellerStoreGroupVo> queryList(ErpSellerStoreGroupBo bo) {
        LambdaQueryWrapper<ErpSellerStoreGroup> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpSellerStoreGroup> buildQueryWrapper(ErpSellerStoreGroupBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpSellerStoreGroup> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getGroupName()), ErpSellerStoreGroup::getGroupName, bo.getGroupName());
        lqw.eq(StringUtils.isNotBlank(bo.getMemo()), ErpSellerStoreGroup::getMemo, bo.getMemo());
        lqw.eq(StringUtils.isNotBlank(bo.getGroupId()), ErpSellerStoreGroup::getGroupId, bo.getGroupId());
        lqw.eq(bo.getParentId() != null, ErpSellerStoreGroup::getParentId, bo.getParentId());
        lqw.eq(bo.getSynchronizationStatus() != null, ErpSellerStoreGroup::getSynchronizationStatus, bo.getSynchronizationStatus());
        lqw.eq(bo.getStatus() != null, ErpSellerStoreGroup::getStatus, bo.getStatus());
        lqw.eq(bo.getStoreId() != null, ErpSellerStoreGroup::getStoreId, bo.getStoreId());
        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpSellerStoreGroup::getRevision, bo.getRevision());
        return lqw;
    }

    /**
     * 新增用户店铺商品分组
     */
    @Override
    public Boolean insertByBo(ErpSellerStoreGroupBo bo) {
        ErpSellerStoreGroup add = BeanUtil.toBean(bo, ErpSellerStoreGroup.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改用户店铺商品分组
     */
    @Override
    public Boolean updateByBo(ErpSellerStoreGroupBo bo) {
        ErpSellerStoreGroup update = BeanUtil.toBean(bo, ErpSellerStoreGroup.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpSellerStoreGroup entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户店铺商品分组
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据店铺id查找可用分组
     *
     * @param storeId
     * @return
     */
    @Override
    public R<Object> queryAvailableGroupsByStoreId(Long storeId) {
        List<ErpSellerStoreGroup> groups = baseMapper.queryAvailableGroupsByStoreId(storeId);
        return R.ok(groups);
    }

    @Override
    public R<Object> createGroupAgain(Long storeId) {
        //1、删除分组
        //找到需要删除的分组
        List<ErpSellerStoreGroup> groupList = baseMapper.selectList(
                new LambdaQueryWrapper<ErpSellerStoreGroup>().eq(ErpSellerStoreGroup::getStoreId, storeId)
        );
        for (ErpSellerStoreGroup group : groupList) {
            List<ErpSellerStoreProductGroup> productGroups = erpSellerStoreProductGroupMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerStoreProductGroup>().eq(ErpSellerStoreProductGroup::getGroupId, group.getGroupId())
            );
            if (productGroups.size() > 0)
                erpSellerStoreProductGroupMapper.deleteBatchIds(productGroups);
        }
        if (groupList.size() > 0)
            baseMapper.deleteBatchIds(groupList);

        Map<String, Object> moduleMap = new HashMap<>();
        String channel = remoteSellerStoreService.getChannelByStoreId(storeId);
        String cookie = remoteSellerStoreService.getCookieByStoreId(storeId);
        moduleMap.put("cookie_str", cookie);
        moduleMap.put("channelId", channel);

        String returnBody = getReturnBody(JSONObject.toJSONString(moduleMap));
        System.out.println(returnBody);
        //分组总数
        BigDecimal groupNum = new BigDecimal(20);
        //具体数据类目
        Map<Long, String> groupMap = new HashMap<>();
        //一级大类目
        Map<Long, String> primaryCategoryMap = new HashMap<>();
        List<Long> categoryList = new ArrayList<>();
        //1 获取一级大类目并创建
        //获取店铺信息
        R<Object> objectR = remoteSellerStoreService.getSellerStoreInfoById(storeId);
        String toJSONString = JSONObject.toJSONString(objectR.getData());
        ErpSellerStoreEmpower store = JSONObject.parseObject(toJSONString, ErpSellerStoreEmpower.class);

        List<ErpCollectProductCategory> primaryCategoryList = erpCollectProductCategoryMapper.queryPrimaryCategoryList(store.getStoreUserName());
        for (ErpCollectProductCategory category : primaryCategoryList) {
            primaryCategoryMap.put(category.getId(), category.getEnName());
            categoryList.add(category.getId());
        }
        BigDecimal rankOneSize = groupNum.subtract(BigDecimal.valueOf(primaryCategoryMap.size()));
        //2 根据销量排名，获取不为0的叶子节点分组
        List<ErpCollectProductCategory> ordersList = erpCollectProductCategoryMapper.queryRankCategoryList(storeId, 0, rankOneSize.intValue());
        if (ordersList.size() >  0){
            for (ErpCollectProductCategory orders : ordersList) {
                groupMap.put(orders.getId(), orders.getEnName());
                categoryList.add(orders.getId());
            }
        }

        //3 根据访客量，获取不为0的叶子节点分组
        BigDecimal rankTwoSize = groupNum.subtract(BigDecimal.valueOf(groupMap.size())).subtract(BigDecimal.valueOf(primaryCategoryMap.size()));
        if (rankTwoSize.compareTo(BigDecimal.ZERO) > 0) {
            List<ErpCollectProductCategory> visitorsList = erpCollectProductCategoryMapper.queryRankCategoryList(storeId, 1, rankTwoSize.intValue());
            if (visitorsList.size() >  0){
                for (ErpCollectProductCategory visitors : visitorsList) {
                    groupMap.put(visitors.getId(), visitors.getEnName());
                    categoryList.add(visitors.getId());
                }
            }
        }

        BigDecimal size = groupNum.subtract(BigDecimal.valueOf(groupMap.size())).subtract(BigDecimal.valueOf(primaryCategoryMap.size()));
        if (size.compareTo(BigDecimal.ZERO) > 0) {
            List<String> categoryListStr = categoryList.stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());
            // 转为字符串
            String categoryStr = String.join(",", categoryListStr);
            //4 根据数量，获取出23之外的优先排序分组
            List<ErpCollectProductCategory> numberList = erpCollectProductCategoryMapper.queryNumberCategoryList(storeId, size.intValue(), categoryStr);
            if (numberList.size()> 0){
                for (ErpCollectProductCategory number : numberList) {
                    groupMap.put(number.getId(), number.getEnName());
                    categoryList.add(number.getId());
                }
            }
        }


        List<String> aeProductIdList = new ArrayList<>();
        List<String> aeProductIdAllList = new ArrayList<>();
        //创建统计数据分组类目
        for (Long categoryId : groupMap.keySet()) {

            List<ErpSellerStoreProduct> erpSellerStoreProductList = erpSellerStoreProductMapper.selectList(
                    new LambdaQueryWrapper<ErpSellerStoreProduct>()
                            .eq(ErpSellerStoreProduct::getStoreId, storeId)
                            .eq(ErpSellerStoreProduct::getCategoryId, categoryId)
                            .isNotNull(ErpSellerStoreProduct::getAeProductId)
            );
            String groupName = groupMap.get(categoryId);
            if (erpSellerStoreProductList.size() <= 10) {
                //小于10个，取上级类目
                ErpCollectProductCategory category = erpCollectProductCategoryMapper.selectOne(
                        new LambdaQueryWrapper<ErpCollectProductCategory>().eq(ErpCollectProductCategory::getId, categoryId)
                );
                ErpCollectProductCategory parentCategory = erpCollectProductCategoryMapper.selectOne(
                        new LambdaQueryWrapper<ErpCollectProductCategory>().eq(ErpCollectProductCategory::getId, category.getParentId())
                );
                groupName = parentCategory.getEnName();
                categoryId = parentCategory.getId();

                erpSellerStoreProductList = erpSellerStoreProductMapper.selectStoreProductListByCategoryId(categoryId, storeId);
            }
            System.out.println(groupName + "(" + erpSellerStoreProductList.size() + ")");
            //创建分组
            String groupId = null;
            R<Object> storeGroup = createGroupByGroupName(groupName, storeId);
            if (storeGroup.getCode() == 200) {
                groupId = (String) storeGroup.getData();
            } else {
                return R.fail("分组异常");
            }

            aeProductIdList = erpSellerStoreProductList.stream()
                    .map(ErpSellerStoreProduct::getAeProductId) // 假设getId是获取id的方法
                    .map(String::valueOf) // 将long类型转换为String类型
                    .collect(Collectors.toList()); //
            aeProductIdAllList.addAll(aeProductIdList);
//            List<String> productIdList = erpSellerStoreProductList.stream()
//                    .map(ErpSellerStoreProduct::getId) // 假设getId是获取id的方法
//                    .map(String::valueOf) // 将long类型转换为String类型
//                    .collect(Collectors.toList()); //
            AddProductGroup(String.join(",", aeProductIdList), Long.valueOf(groupId));
        }


        //创建一级大类目
        for (Long categoryId : primaryCategoryMap.keySet()) {
            String groupName = primaryCategoryMap.get(categoryId);
            //创建分组
            String groupId = null;
            R<Object> storeGroup = createGroupByGroupName(groupName, storeId);
            if (storeGroup.getCode() == 200) {
                groupId = (String) storeGroup.getData();
            } else {
                return R.fail("分组异常");
            }
            String IdSize = null;
            if (aeProductIdAllList.size()>0){
                IdSize = String.join(",", aeProductIdAllList);
            }else {
                IdSize = null;
            }
            List<ErpSellerStoreProduct> erpSellerStoreProductList = erpSellerStoreProductMapper.selectPrimaryCategoryList(
                    store.getStoreUserName(),IdSize , categoryId
            );
            List<String> productIdList = erpSellerStoreProductList.stream()
                    .map(ErpSellerStoreProduct::getAeProductId) // 假设getId是获取id的方法
                    .map(String::valueOf) // 将long类型转换为String类型
                    .collect(Collectors.toList()); //
            AddProductGroup(String.join(",", productIdList), Long.valueOf(groupId));

        }

        //记录标记
        return null;
    }


    public R<Object> AddProductGroup(String productIds, Long groupId) {
        R<Object> objectR = erpSellerStoreProductGroupService
                .bindingProdudtForGroup(productIds, groupId);
        Map<String, Object> map = (Map<String, Object>) objectR.getData();
        //添加该商品到速卖通分组中
        SendProductGroupDto dto = new SendProductGroupDto();
        dto.setStoreId((String) map.get("storeId"));
        dto.setProductGroups((String) map.get("productGroups"));
        dto.setGroupId((String) map.get("groupId"));
        R<Object> objectR1 = remoteAeStoreGroupService.bindingProdudtForGroup(dto);
        //用mq的方式，进行分配
//        rabbitTemplate.convertAndSend("auto-event-exchange", "auto.store.group.create", JSONObject.parseObject(map.toString()));
//        erpSellerStoreProductGroupService.sendProductGroupToAe(map);
        return R.ok();
    }

    public R<Object> createGroupByGroupName(String groupName, Long storeId) {
        groupName =  groupName ;
        if (groupName.length() - 45 > 0) {
            //如果字符长度大于45，则切分
            List<String> groupNameList = new ArrayList<>();
            if (groupName.contains("&")) {
                groupNameList = Arrays.asList(groupName.split("&"));
            }
            if (groupName.contains("/")) {
                groupNameList = Arrays.asList(groupName.split("/"));
            }
            String endGroupName = groupNameList.get(0);
            groupName = endGroupName;
        }

        //同步分组
//        iAeProductService.queryStoreGroupList(storeId);

        ErpSellerStoreGroup groupSel = baseMapper.selectOne(
                new LambdaQueryWrapper<ErpSellerStoreGroup>()
                        .eq(ErpSellerStoreGroup::getGroupName, groupName)
                        .eq(ErpSellerStoreGroup::getStoreId, storeId)
        );
        if (Objects.isNull(groupSel)) {
            //不存在则创建分组
            StoreGroupDto dto = new StoreGroupDto();
            dto.setGroupName(groupName);
            dto.setStoreId(storeId);
            dto.setMemo(groupName);
            dto.setParentId(0L);
            R<Object> storeGroup = remoteAeStoreGroupService.createStoreGroup(dto);
            if (storeGroup.getCode() == 200) {
                String storeGroupStr = (String) storeGroup.getData();
                System.out.println(storeGroupStr);
                JSONObject storeGroupJson = JSONObject.parseObject(storeGroupStr);
                //创建成功，拿到对应值
                groupSel = new ErpSellerStoreGroup();
                groupSel.setGroupName(groupName);
                groupSel.setStoreId(storeId);
                groupSel.setMemo(groupName);
                groupSel.setGroupId(
                        storeGroupJson
                                .getJSONObject("aliexpress_postproduct_redefining_createproductgroup_response")
                                .getJSONObject("result")
                                .getString("target")
                );
                groupSel.setParentId(0L);
                groupSel.setStatus(1);
                baseMapper.insert(groupSel);
            }
//            else {
//                //使用一级分类的分组
//              ErpCollectProductCategory  category = erpCollectProductCategoryMapper.selectById(categoryAncestorsList.get(1));
//                groupSel = erpSellerStoreGroupMapper.selectOne(
//                        new LambdaQueryWrapper<ErpSellerStoreGroup>()
//                                .eq(ErpSellerStoreGroup::getGroupName, category.getEnName())
//                                .eq(ErpSellerStoreGroup::getStoreId, storeId)
//                );
//            }
        }
        if (ObjectUtils.isNull(groupSel)) {
            return R.fail("分组异常");
        } else {
            String groupId = groupSel.getGroupId();
            return R.ok(groupId);
        }
    }

    private String getReturnBody(String moduleMap) {
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost("http://47.94.131.193:8000/delete/group");
        post.setHeader("Content-Type", "application/json;charset=utf-8");
        post.setHeader("Accept", "application/json");
        post.setHeader("Content-Encoding", "gzip");
        post.setEntity(new StringEntity(moduleMap, StandardCharsets.UTF_8));
        HttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(post);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        HttpEntity response = httpResponse.getEntity();
        try {
            return EntityUtils.toString(response, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
